package com.gss.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gss.common.core.service.BaseServiceImpl;
import com.gss.datasource.mapper.sys.SysDeptRoleMapper;
import com.gss.datasource.mapper.sys.SysRoleMenuMapper;
import com.gss.entity.R;
import com.gss.entity.enums.ConstantEnum;
import com.gss.entity.sys.dto.SysDeptRole;
import com.gss.entity.sys.dto.SysMenu;
import com.gss.entity.sys.dto.SysRole;
import com.gss.entity.sys.dto.SysRoleMenu;
import com.gss.entity.sys.vo.SysRoleMenuVo;
import com.gss.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author DYang
 * @date 2023/6/17
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysDeptRoleMapper deptRoleMapper;

    @Transactional
    @Override
    public R<String> oauthMenu(SysRoleMenuVo entity) {
        Integer roleId = entity.getId();
        List<SysMenu> menuList = entity.getMenuList();
        if (roleId == null || menuList == null) {
            return R.error(ConstantEnum.PARAM_ERROR);
        }
        for (SysMenu sysMenu : menuList) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(sysMenu.getId());
            roleMenu.setCreateTime(new Date());

            sysRoleMenuMapper.insert(roleMenu);
        }
        return R.ok("新增成功");
    }

    @Override
    public R<String> deleteMenu(List<Integer> idList) {
        QueryWrapper<SysDeptRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",idList);

        Long count = deptRoleMapper.selectCount(queryWrapper);
        if (count != null && count > 0) {
            return R.error(ConstantEnum.USING_ERROR);
        }
        int batch = deptRoleMapper.deleteBatchIds(idList);
        return batch > 0 ? R.ok("删除成功") : R.error(ConstantEnum.DEL_ERROR);
    }
}
